package com.vestore.vestoretest.vestore;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONArray;
import com.rtdb.api.model.RtdbData;
import com.rtdb.api.model.ValueData;
import com.rtdb.api.util.DateUtil;
import com.rtdb.enums.RtdbHisMode;
import com.rtdb.model.*;
import com.rtdb.service.impl.*;
import com.rtdb.service.inter.Base;
import com.rtdb.service.inter.Historian;
import com.rtdb.service.inter.Snapshot;
import com.vestore.vestoretest.model.CombinedData;
import com.vestore.vestoretest.model.ProductionCurve;
import com.vestore.vestoretest.utils.HttpUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ArrayUtils;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

@Slf4j
@Controller
@RequestMapping("/obtainMeasurement")
public class ObtainMeasurementController {
    private static Snapshot snap = null;
    private static Base base = null;
    private static Historian his;
    private static ServerImpl server = null;
    //IProductionCurveService productionCurveService = SpringContextHolder.getBean(IProductionCurveService.class);
    //获取手动维护数据
    public static String URL = "http://10.2.80.248:8100/api/portal/open/get-portal-detail";

    //获取安全生产天数数据
    public static String URL2 = "http://10.2.80.248:8100/api/riskData/open/statisticalDays";
    //实时取数
    private static String[] myArrayOne1 = new String[]{"XNJS.10_AM13MKA01_50", "DCS1.10_LBA10CT601", "DCS1.10_AMLBB20CT601M",
            "DCS1.10_AM44HTA40CQ101", "DCS1.10_AM44HTA40CQ104", "DCS1.10_AM44HTA40CQ103", "DCS1.10_AMMAG10CP1M"};
    private static String[] myArrayOne2 = new String[]{"XNJS.20_AM13MKA01_50", "DCS2.20_LBA10CT601", "DCS2.20_AMLBB20CT601M",
            "DCS2.20_AM44HTA40CQ101", "DCS2.20_AM44HTA40CQ104", "DCS2.20_AM44HTA40CQ103", "DCS2.20_AMMAG10CP1M"};
    //历史取数
    private static String[] myArrayTwo = new String[]{"XNJS.PE_DRLJDL", "XNJS.PE_GR_LJLLLJ_DR", "XNJS.0_YFDL",
            "XNJS.PE_DNLJDL", "XNJS.PE_GR_LJLLLJ_DY", "XNJS.PE_GR_LJLLLJ_DN"};
    //曲线图
    private static String[] myArrayThree = new String[]{"XNJS.PE_SSFH", "XNJS.10_AM13MKA01_50", "XNJS.20_AM13MKA01_50", "XNJS.PE_SSGRLL",
            "DCS1.GR_ZHPL_ZLSSLL_001", "DCS1.GR_DP_SSLL_005", "DCS1.GR_YDLY_ZLSSLL_002", "DCS1.GR_HKYJD_ZLSSLL_006"};

    public static DecimalFormat nf = new DecimalFormat("#0.00");

    //获取实时测点数据
    @RequestMapping("getSnapshots")
    @ResponseBody
    public String getSnapshots() {
        JSONObject jsonObject = new JSONObject();
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-M-d");
        Date date = new Date();
        calendar.setTime(date);
        calendar.add(Calendar.DATE, -1);
        String time = format.format(calendar.getTime());
        Map<String, String> param = new HashMap<>();
        param.put("date", time);
        try {
            ServerImplPool pool = new ServerImplPool("10.2.80.121", 6327, "sa", "VeStore-123#!", 5, 10);
            server = pool.getServerImpl();
            snap = new SnapshotImpl(server);
            base = new BaseImpl(server);
            //一号机组
            List<MinPoint> minPointList = base.findPoints(myArrayOne1);
            List<Integer> integerList = minPointList.stream().map(item -> {
                return item.getId();
            }).collect(Collectors.toList());
            Integer[] integers = integerList.toArray(new Integer[0]);
            //获取全局变量
            List<FullPoint> fullPointEntity = base.getPointsProperties(ArrayUtils.toPrimitive(integers)).getList();//处理数据
            List<ValueData> valueDataList = snap.getSnapshots(ArrayUtils.toPrimitive(integers));
            //合并数据1号机组
            List<CombinedData> combinedData = this.combineLists(fullPointEntity, valueDataList);
            //二号机组
            List<MinPoint> minPointList2 = base.findPoints(myArrayOne2);
            List<Integer> integerList2 = minPointList2.stream().map(item -> {
                return item.getId();
            }).collect(Collectors.toList());
            Integer[] integers2 = integerList2.toArray(new Integer[0]);
            //获取全局变量
            List<FullPoint> fullPointEntity2 = base.getPointsProperties(ArrayUtils.toPrimitive(integers2)).getList();
            //处理数据
            List<ValueData> valueDataList2 = snap.getSnapshots(ArrayUtils.toPrimitive(integers2));
            //#2数据
            List<CombinedData> combinedData2 = this.combineLists(fullPointEntity2, valueDataList2);
            //传出#1数据
            combinedData.forEach(item -> {
                jsonObject.put(item.getTableDotTag(), this.getDoubleValue(item.getValue()));
            });
            //传出#2数据
            combinedData2.forEach(item -> {
                jsonObject.put(item.getTableDotTag(), this.getDoubleValue(item.getValue()));
            });
            //传出全厂累计发电（日、月、年）（发电、供热）
            List<CombinedData> crossSectionValues = this.getCrossSectionValues();
            crossSectionValues.forEach(item -> {
                jsonObject.put(item.getTableDotTag(), this.getDoubleValue(item.getValue()));
            });
            //获取手动维护数据
            JSONObject res = HttpUtils.doGet(URL, param);
            if ("00000".equals(res.get("code"))) {
                JSONObject data = new JSONObject();
                data = (JSONObject) res.get("data");
                if (data != null) {
                    JSONArray jsonArray = JSON.parseArray(data.getString("jsonData"));
                    for (int i = 0; i < jsonArray.size(); i++) {
                        JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                        jsonObject.put(jsonObject1.getString("key"), !StringUtils.isEmpty(jsonObject1.getString("value")) ? nf.format(jsonObject1.getDouble("value")) : "0");
                    }
                }
            }
            //获取安全生产天数
            for (int i = 0; i < 3; i++) {
                Map<String, String> param1 = new HashMap<>();
                param1.put("num", String.valueOf(i));
                JSONObject result = HttpUtils.doGet(URL2, param1);
                int num = 0;
                if ("00000".equals(result.get("code"))) {
                    JSONObject data = new JSONObject();
                    data = (JSONObject) result.get("data");
                    if (1 == data.getInteger("status")) {
                        num = data.getInteger("day");
                    }
                    switch (i) {
                        case 0:
                            jsonObject.put("wholePlant", num);//全厂
                            break;
                        case 1:
                            jsonObject.put("wholePlant1", num);//1机组
                            break;
                        case 2:
                            jsonObject.put("wholePlant2", num);//2机组
                            break;
                    }
                }
            }
            jsonObject.put("time",format.format(date));
            base.close();
            snap.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject.toJSONString();
    }

    //传出全厂累计发电（日、月、年）（发电、供热）
    public List<CombinedData> getCrossSectionValues() {
        List<CombinedData> combinedData = new ArrayList<>();
        try {
            ServerImplPool pool = new ServerImplPool("10.2.80.121", 6327, "sa", "VeStore-123#!", 5, 10);
            his = new HistorianImpl(pool.getServerImpl());
            base = new BaseImpl(pool.getServerImpl());
            List<MinPoint> minPointList = base.findPoints(myArrayTwo);
            List<Integer> integerList = minPointList.stream().map(item -> {
                return item.getId();
            }).collect(Collectors.toList());
            Integer[] integers = integerList.toArray(new Integer[0]);
            //获取全局变量
            List<FullPoint> fullPointEntity = base.getPointsProperties(ArrayUtils.toPrimitive(integers)).getList();
            List<ValueData> valueDataList = snap.getSnapshots(ArrayUtils.toPrimitive(integers));
            combinedData = this.combineLists(fullPointEntity, valueDataList);
            his.close();
            base.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return combinedData;
    }

    public double getDoubleValue(Double getDoubleValue) {
        BigDecimal bd = new BigDecimal(Double.toString(getDoubleValue));
        bd = bd.setScale(2, RoundingMode.HALF_UP);
        double roundedValue = bd.doubleValue();
        return roundedValue;
    }

    //将根据id封装数据（名称、测点值、测点描述）
    List<CombinedData> combineLists(List<FullPoint> fullPointEntity, List<ValueData> valueDataList) {
        Map<Integer, ValueData> valueDataMap = valueDataList.stream()
                .collect(Collectors.toMap(ValueData::getId, valueData -> valueData));
        List<CombinedData> combinedList = new ArrayList<>();
        for (FullPoint point : fullPointEntity) {
            BasePoint basePoint = point.getBasePoint();
            ValueData valueData = valueDataMap.get(basePoint.getId());
            if (valueData != null) {
                CombinedData combinedData = new CombinedData();
                combinedData.setId(basePoint.getId());
                combinedData.setTableDotTag(basePoint.getTable_dot_tag());
                combinedData.setDesc(basePoint.getDesc());
                combinedData.setValue(this.getDoubleValue(valueData.getValue()));
                combinedList.add(combinedData);
            }
        }
        return combinedList;
    }

    //echars图数据定时获取
    @RequestMapping("getSnapshotsEcharts")
    @ResponseBody
    public String getSnapshotsEcharts() {
        JSONObject jsonObject = new JSONObject();
        try {
            ServerImplPool pool = new ServerImplPool("10.2.80.121", 6327, "sa", "VeStore-123#!", 2, 4);
            server = pool.getServerImpl();
            snap = new SnapshotImpl(server);
            base = new BaseImpl(server);
            List<MinPoint> minPointList = base.findPoints(myArrayThree);
            List<Integer> integerList = minPointList.stream().map(item -> {
                return item.getId();
            }).collect(Collectors.toList());
            Integer[] integers = integerList.toArray(new Integer[0]);
            //获取全局变量
            List<FullPoint> fullPointEntity = base.getPointsProperties(ArrayUtils.toPrimitive(integers)).getList();
            //处理数据
            List<ValueData> valueDataList = snap.getSnapshots(ArrayUtils.toPrimitive(integers));
            List<CombinedData> combinedData = this.combineLists(fullPointEntity, valueDataList);
            ProductionCurve productionCurve = new ProductionCurve();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:00");
            Date date = new Date();
            String timeString = sdf.format(date);
            List<ProductionCurve> productionCurves = new ArrayList<>();
            combinedData.forEach(cd -> {
                productionCurve.setPoint(cd.getTableDotTag());
                productionCurve.setTime(timeString);
                productionCurve.setValue(this.getDoubleValue(cd.getValue()) + "");
                productionCurves.add(productionCurve);
            });
            jsonObject.put("productionCurves", productionCurves);
//            if (!productionCurves.isEmpty() && productionCurveService.insertBatch(productionCurves)) {
//                log.info(timeString + "生产信息曲线更新成功！");
//            } else {
//                log.info(timeString + "生产信息曲线更新失败！");
//            }
            base.close();
            snap.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject.toJSONString();
    }
}